package com.by.service.impl;

import com.by.bean.Dept;
import com.by.common.crud.BaseServiceImpl;
import com.by.mapper.DeptMapper;
import com.by.query.DeptQuery;
import com.by.service.DeptService;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class DeptServiceImpl extends BaseServiceImpl<Dept, DeptMapper> implements DeptService {

    @Override
    public int save(Dept entity) {
        //生成部门编码
        entity.setDeptCode(generateDeptCode(entity.getParentId()));
        return super.save(entity);
    }

    @Override
    public int delete(Serializable id) {
        //删除部门时,需要判断是否有子部门,如果有子部门,则不能删除
        int c = baseMapper.queryChildCount(id);
        if (c > 0)return 2;//有子部门,不能删除
        return super.delete(id);
    }

    /**
     * 生成编码
     * @param parentId
     * @return
     */
    String generateDeptCode(int parentId) {
        //根据父部门ID生成部门编码
        String maxCode = baseMapper.queryMaxCode(parentId);
        if (maxCode == null) {
            //说明在父id为 parentId时,子部门还没有 子部门的编码为 01
            //确认父编码
            if (parentId == 0){
                //说明添加的是顶级部门
                return "101";
            }
            //parentId != 0 查询对应的部门编码
            String parentCode = baseMapper.queryCodeById(parentId);
            return parentCode + "01";
        }
        //如果存在最大编码,则在最大编码的末尾加1
        Integer tmp = Integer.parseInt(maxCode);
        tmp++;
        return String.valueOf(tmp);
    }


    @Override
    public List queryTree() {
        return baseMapper.queryTree(0);
    }

    @Override
    public int updateStatus(int id, int status) {
        return baseMapper.updateStatus(id, status);
    }

    @Override
    public List<Map> queryChildDept(DeptQuery query) {
        return baseMapper.queryChildDept(query);
    }
}
